<?php

namespace app\yj\controller;

use app\yj\model\DataModel;
use app\yj\model\DataTypeModel;
use app\yj\model\FailepModel;
use app\yj\model\FileModel;
use app\yj\model\QuyuModel;
use app\yj\model\UserModel;
use think\Controller;
use think\Error;
use think\Request;

class DataController extends BaseAdminController
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index(Request $request)
    {
        $page = $request->get('page');
        $size = $request->get('size');
        $id = $request->get('id');
        $title = $request->get('title');
        $createTime_min = $request->get('createTime_min');
        $createTime_max = $request->get('createTime_max');
        $solve = $request->get('solve');
        $level = $request->get('level');

        //管理员获取全部的data
        if (self::$user['roles'] == 0) {
            $datasql = DataModel::order('id', 'desc');
            if ($page) $datasql->limit(($page - 1) * $size, $size);
            if ($id) $datasql->where('id', $id);
            if ($solve) $datasql->where('solve', $solve);
            if ($level) $datasql->where('level', $level);

            if ($title) $datasql->where('title', 'like', '%' . $title . '%');
            if ($createTime_min) $datasql->where('time', '>=', $createTime_min);
            if ($createTime_max) $datasql->where('time', "<=", $createTime_max);

            $datas = $datasql->select()->toArray();
            $count = $datasql->count();
//            foreach ($datas as $k => $v) {
//                if ($v['type'] == 'polygon') {
//                    if ($v['gdid'] != '' && count($v['gdid']) > 0) {
//                        $datas[$k]['failps'] = FailepModel::where('gdid', $v['gdid'])->select()->toArray();
//                    }
//                }
//            }
        } else {
            //判断区域数据
//
            if (self::$user['qyid'] != '') {

                $quyu = QuyuModel::find(self::$user['qyid']);

                $allquyu = QuyuModel::where('fid', 'like', $quyu->fid . "%")->select()->toArray();
                $dids = [];
                $datasql = DataModel::where(1, '=', 1);
                if ($id) $datasql->where('id', $id);
                if ($solve) $datasql->where('solve', $solve);
                if ($level) $datasql->where('level', $level);

                if ($title) $datasql->where('title', 'like', '%' . $title . '%');
                if ($createTime_min) $datasql->where('time', '>=', $createTime_min);
                if ($createTime_max) $datasql->where('time', "<=", $createTime_max);


                $datas = $datasql->select()->toArray();
                foreach ($allquyu as $v) {

                    foreach ($datas as $d) {

                        if (in_array($v['id'], $d['qyid'])) {

                            //在里面
                            array_push($dids, $d['id']);
                        }
                    }
                }
                $dids = array_unique($dids);
                $datas = [];
                //获取区域下所有的数据
                foreach ($dids as $v) {
                    $data = DataModel::find($v);

//                   
//                    if ($data) {
//                        //判断是否管道
//                        if ($data['type'] == 'polygon') {
//                            if ($data['gdid'] != '' && count($data['gdid']) > 0) {
//                                $data['failps'] = FailepModel::where('gdid', $data['gdid'])->select()->toArray();
//                            }
//                        }
                    array_push($datas, $data);
//                    }
                }
                $count = count($dids);
//                return $this->SuccessReturn('ok', $datas);

//                $datas = [];
//                foreach ($users as $v) {
//                    $data = DataModel::where('uid', $v['id'])->select()->toArray();
//
//                    if (count($data) > 0) {
//                        foreach ($data as $v) {
//                            array_push($datas, $v);
//                        }
//                    }
//                }
            }


        }

        return $this->SuccessReturn('ok', $datas, $count);
    }

    public function getAllFile($fid = 0)
    {
        $files = FileModel::where('fid', $fid)
            ->with("data")
            ->where("uid", self::$user['id'])
            ->select()->toArray();

        if (count($files) > 0) {
            foreach ($files as $v) {
                //获取下级
                $res = FileModel::where('fid', $v['id'])
                    ->where('uid', self::$user['id'])
                    ->find();
                if ($res) {
                    $v['children'] = $this->getAllFile($v['id']);
                }
            }
            return $files;
        } else {
            return $files;
        }
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
        $data = $request->post();
        //获取参数
        if ($data == '') return $this->ErrorReturn(403, "缺少必要参数");
        $res_data = [];
        $latlng = array_key_exists('latlng', $data) ? $data['latlng'] : [];
        $title = array_key_exists('title', $data) ? $data['title'] : '未定义';

        $config = array_key_exists('config', $data) ? $data['config'] : '';
        $context = array_key_exists('context', $data) ? $data['context'] : '';
        $time = array_key_exists('time', $data) ? $data['time'] : time();
        $files = array_key_exists('files', $data) ? $data['files'] : [];
        $time = array_key_exists('time', $data) ? $data['time'] : time();

        $solve = array_key_exists('solve', $data) ? $data['solve'] : 0;
        $level = array_key_exists('level', $data) ? $data['level'] : 1;
//        $solvetime = array_key_exists('time', $data) ? $data['time'] : time();

        if ($latlng != '') {
            //存储数据
            //检查latlng 是否是标准的
            $new_data = new DataModel();
            $new_data->context = $context;
            $new_data->config = $config;
            $new_data->time = $time;
            $new_data->files = $files;
            $new_data->latlng = $latlng;
            $new_data->title = $title;
            $new_data->level = $level;
            $new_data->solve = $solve;

            $new_data->save();
            $res_data = $new_data;
        }


//        if ($name == '' || $type == '' || $latlng == '') {
//            return $this->ErrorReturn(403, '缺少参数', $data);
//        }

        return $this->SuccessReturn('添加成功', $res_data);
    }

    /**
     * 显示指定的资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
        //
        $data = $request->put();
        //获取参数
        $id = array_key_exists('id', $data) ? $data['id'] : '';

        $latlng = array_key_exists('latlng', $data) ? $data['latlng'] : "";
        $config = array_key_exists('config', $data) ? $data['config'] : '';
        $context = array_key_exists('context', $data) ? $data['context'] : '';
        $see = array_key_exists('context', $data) ? $data['context'] : '';
        $files = array_key_exists('files', $data) ? $data['files'] : '';
        $title = array_key_exists('title', $data) ? $data['title'] : '';

        if ($id == '') return $this->ErrorReturn(403, '缺少必要参数', $data);
        $id = ltrim($id, '000');


        //查询修改的对象
        $data_res = DataModel::find($id);
        if (!$data_res) return $this->ErrorReturn(400, '查询不到对象');

        if ($config != '') $data_res->config = $config;
        if ($files != '') $data_res->files = $files;
        if ($context != '') $data_res->context = $context;
        if ($see != '') $data_res->see = $see;
        if ($latlng != '') $data_res->latlng = $latlng;
        if ($title != '') $data_res->title = $title;
        if (array_key_exists('solve', $data)) {
            $data_res->solve = $data['solve'];
            if ($data_res->solvetime == '') {
                $data_res->solvetime = time();
            }
        }
        array_key_exists('level', $data) ? $data_res->level = $data['level'] : '';

//        if ($latlng != '') {
//            //检查latlng 是否正确
//            $lng = (float)$latlng[$i];
//            $lat = (float)$latlng[$i + 1];
//            if (-90 < $lat && $lat < 90 && -180 < $lng && $lng < 180) {
//
//            }
//        }
//        $data_res['icon'] = $data_res->icon;
        $res = $data_res->save();
        if ($res) return $this->SuccessReturn('修改成功', $data_res);
        return $this->ErrorReturn(400, '修改失败');
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($id, Request $request)
    {
        //

        //查询是否存在此用户
        $data = DataModel::where('id', $id)->find();
        if (!$data) return $this->ErrorReturn(404, '找不到此数据');
        $data->delete();
        return $this->SuccessReturn('删除成功');
    }


    public function delAllData(Request $request)
    {
        $ids = $request->post('ids');

        if (!is_array($ids)) {
            return $this->ErrorReturn(400, '没获取到数组');
        }

        foreach ($ids as $v) {
            $data = DataModel::find($v);
            if ($data) $data->delete();
        }
        return $this->SuccessReturn('删除成功');

    }

    public function uploaduserfile(Request $request)
    {
        //定义假用户
        self::$user['id'] = 1;
        $file = $request->file();

        if (!$file) return $this->SuccessReturn('暂无文件保存');

        //保存文件
        $nowtime = time();

        $user_path = '../public/file/user' . self::$user['id'];

        $info = $file['file']->move($user_path);
        $sername = $request->server('REQUEST_SCHEME') . '://' . $request->server('SERVER_NAME');
        if ($info) {
            // 输出 jpg
//            return $info->getExtension();
            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
            $name = $info->getSaveName();
            $savename = $sername . "/file/user" . self::$user['id'] . "/" . $name;

            return $this->SuccessReturn('ok', ['url' => $savename, 'name' => $file['file']->getInfo('name')]);
        }
        return $this->ErrorReturn(400, "上传失败");
    }

    public function getNewData(Request $request)
    {
        $nowtime = time();
        $datas = DataModel::where('time', '>', $nowtime - 3)
            ->select();
        return $this->SuccessReturn('ok', $datas);
    }

    //获取指定时间内的数据
    public function getTimeCount(Request $request)
    {
        $datas = $request->post();

        $days = $request->post('day');
        $solve = $request->post('solve');
        $level = $request->post('level');
        if ($days != null) {
            //获取3个月内的
            $daytime = strtotime(date("Y-m-d", strtotime("-" . $days . "day")));
            $datasql = DataModel::where('time', '>', $daytime);
            if ($solve != null) $datasql->where('solve', $solve);
            if ($level != null) $datasql->where('level', $level);

            $datas = $datasql->select()->toArray();

            //处理时间
            foreach ($datas as $k => $v) {
                $datas[$k]['month'] = date('m', $v['time']);
            }
            return $this->SuccessReturn('ok', $datas);
        }


//        //获取当天的时间戳
//        $today = strtotime(date("Y-m-d"), time());

        //获取上个月的第一天
        $month = $request->post('month');
        if ($month != null) {
//            $month -= 1;
            $monthfirst = strtotime(date("Y-m-01", strtotime("-" . $month . "month")));
            $datasql = DataModel::where('time', '>', $monthfirst);
            if ($solve != null) $datasql->where('solve', $solve);
            if ($level != null) $datasql->where('level', $level);
            $datas = $datasql->select()->toArray();
            foreach ($datas as $k => $v) {
                $datas[$k]['month'] = date('m', $v['time']);
            }

            return $this->SuccessReturn('ok', $datas);
        }
    }

    //改变事件 解决了
    public function solveData(Request $request)
    {
        $id = $request->post('id');
        $solve = $request->post('solve');
        if ($solve == null) return $this->ErrorReturn(500, '没获取到solve参数');
        $data = DataModel::find($id);
        if (!$data) return $this->ErrorReturn(500, '没获取到数据');
        $solvetime = '';
        if ($solve == 1) {
            $solvetime = time();
        }
        $data->solve = $solve;
        $data->solvetime = $solvetime;
        $data->save();
        return $this->SuccessReturn($data);
    }
}
